package com.wxh.controller;

import com.aliyuncs.exceptions.ClientException;
import com.wxh.constant.MessageConstant;
import com.wxh.constant.RedisMessageConstant;
import com.wxh.entity.Result;
import com.wxh.pojo.Order;
import com.wxh.service.OrderService;
import com.wxh.utils.SMSUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

@RestController
@RequestMapping("/order")
public class OrderController {
    @Autowired
    private JedisPool jedisPool;
    @Reference
    private OrderService orderService;

    @RequestMapping("/submitOrder")
    public Result submit(@RequestBody Map map) {
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        String validateCodeInRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
        if (validateCodeInRedis == null || !validateCodeInRedis.equals(validateCode)) {
            return new Result(false, MessageConstant.VALIDATECODE_ERROR);
        }
            try {
                map.put("orderType", Order.ORDERTYPE_WEIXIN);
                Result result = orderService.order(map);
                if (result.isFlag()) {
                    String orderDate = (String) map.get("orderDate");
                    try {
                        SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, telephone, orderDate);
                    } catch (ClientException e) {
                        e.printStackTrace();
                        return new Result(false, "通知短信发送失败！");
                    }
                }
                return result;
            } catch (Exception e) {
                e.printStackTrace();
                return new Result(false, "预约失败");
            }
        }
    @RequestMapping("/findById")
    public Result findById(Integer id){
        try{
            Map map = orderService.findById(id);
            return new Result(true,MessageConstant.QUERY_ORDER_SUCCESS,map);
        }catch (Exception e){
            e.printStackTrace();
            return new Result(false,MessageConstant.QUERY_ORDER_FAIL);
        }
    }
}
